<template>
  <div class="page-item pre-page" id="page-item" ref="prePage">
    <div id="testDiv"></div>
    <div class="w-content-wrap page-box">
      <template v-for="(item, index) in pageList">
        <!-- type为1的时候title -->
        <w-title
          v-if="
            item.detailType == 1 ||
              item.detailType == 2 ||
              item.detailType == 3 ||
              item.detailType == 4 ||
              item.detailType == 0
          "
          :title="JSON.parse(item.data).data"
          :level="item.detailType"
          :id="item.htmlId"
        ></w-title>
        <!-- type为2的时候table -->
        <w-table
          v-if="item.detailType == 11"
          :id="item.htmlId"
          :tableData="JSON.parse(item.data).data"
          :config="JSON.parse(item.data).config"
          :tableName="JSON.parse(item.data).name"
        ></w-table>
        <!-- type为3的时候echarts -->
        <w-charts
          v-if="item.detailType == 10"
          :id="item.htmlId"
          :itemData="JSON.parse(item.data)"
          :width="JSON.parse(item.data).width"
          :height="JSON.parse(item.data).height"
        ></w-charts>
        <!-- type为4的时候text -->
        <wText
          v-if="item.detailType == 5"
          :message="JSON.parse(item.data).data"
          :className="JSON.parse(item.data).cssName"
          :id="item.htmlId"
        ></wText>
        <div
          v-if="item.detailType == 12 || item.detailType == 13"
          v-html="JSON.parse(item.data).data"
          :id="item.htmlId"
          :class="[
            JSON.parse(item.data).cssName != ''
              ? JSON.parse(item.data).cssName + ' m-bottom'
              : 'm-bottom'
          ]"
        ></div>
      </template>
    </div>
  </div>
</template>

<script>
import store from '../store/index'
import { mapState } from 'vuex'
import wTitle from '../components/title'
import wText from '../components/text'
import wTable from '../components/table'
import wCharts from '../components/echarts'
import chartMixins from '../components/mixins/chartMixins'
export default {
  name: 'pagePreItem',
  props: {
    reportId: {
      type: String
    },
    levelIndex: {
      type: String
    }
  },
  computed: {
    ...mapState(['home'])
  },
  mixins: [chartMixins],
  components: {
    wTitle,
    wText,
    wTable,
    wCharts
  },
  data() {
    return {
      page: 1,
      pageList: [],
      list: [],
      nextDomH: 0,
      newDiv: '',
      chartData: {},
      deleteNum: 0,
      ifSmall: 0,
      dataArr: [], // 一页可放下的数据组
      ids: [], // 一页可放下内容的ID组
      testNum: 0
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getPageInit1() //获取所有的页面数据
    })


  },
  methods: {
    // 获取页面信息
    getpage(pageList) {
      let pageH = document.getElementsByClassName('w-content-wrap')[0]
        .offsetHeight // 获取页面高度
      let itemDomH = 0 // 当前页内容累加高度
      let surplusH = 0 // 超出高度
      let ifReduce = false // 是否被裁剪
      this.newDiv = document.getElementById('testDiv') // 用来测量文字是否需要拆分、何处拆分
      pageList.forEach((item, index) => {
        // 循环处理
        if (item.detailType == '10') {
          //当前项是echart图表类型的话
          itemDomH += document.getElementById(item.htmlId).offsetHeight + 30 // 获取当前页高度
        } else {
          itemDomH += document.getElementById(item.htmlId).offsetHeight // 获取当前页高度
        }
        // console.log( itemDomH  );
        // 判断当前累加高度是否超过页面高度
        if (itemDomH > pageH) {
          // 超过
          surplusH = itemDomH - pageH // 获取超出的高度
          // console.log('11111111111111111111111111');
          this.ClientDom(surplusH, item, this.page, pageH) // 调用裁剪数据的方法
          ifReduce = true
          itemDomH = this.nextDomH
        } else {
          // 未超过
          if (item.detailType == '5' || item.detailType == '10') {
            // 当detailType为5时，margin-bottom为20 其余为10
            itemDomH += 20
          } else {
            itemDomH += 10
          }
          ifReduce = false
          // 将可以放下的数据push进此页list
          this.dataArr.push(item)
          this.ids.push(item.htmlId)
          // console.log( this.list );

          this.list[this.page - 1] = {
            page: this.page,
            data: this.dataArr,
            ids: this.ids
          }
        }
      })
      this.newDiv.remove()
      if( this.list[this.list.length - 1].data.length == 0 ) {
        this.list.length = this.list.length - 1;
      }
      this.list[this.list.length - 1].isLast = true;

      console.log( this.list );
      store.commit('home/getList', this.list);
    },
    // detailType == 1、2、3、4、0 标题; （直接下一页显示）
    // detailType == 5 文字; （需要对数据进行切分）
    // detailType == 11 表格; （需要对数据进行切分，存在切分多次的情况）
    // detailType == 10 Echarts图表; （直接下一页显示）
    // detailType == 12、13 图片/html标签;（直接下一页显示）
    ClientDom(surplusH, item, page, pageH) {
      // console.log( '页数:', page);
      this.testNum = 0
      let firstData = null // 拆分的第一段数据
      let secondData = null // 拆分的第二段数据
      let secondID = null // 第二段id
      let boxH = document.getElementById(item.htmlId).getBoundingClientRect()
        .height // 获取超出元素的高度

      let ifNext = true;
      // 表格时
      if (item.detailType == '11') {
        let allData = JSON.parse(item.data)
        let tableData = allData.data // 表格内数据
        let config = allData.config // 表头数据
        let tableName = allData.name // 表格名字

        let breakNum = 0 // 从何处开始截断数据
        let useNum = 0
        let ifBreak = 1
        let tableHeadClass = document
          .getElementById(item.htmlId)
          .getElementsByClassName('el-table__header-wrapper')[0].offsetHeight // 当前表格表头高度
        let tableClass = document
          .getElementById(item.htmlId)
          .getElementsByClassName('el-table__row') // 获取当前ID里所有数据表格
        if (tableClass.length == 0) {
          tableClass = document
            .getElementById(item.htmlId)
            .getElementsByClassName('el-table__empty-block')
        }
        let tableArray = Array.prototype.slice.call(tableClass) // 获取到的是伪数组类型，需要转成数组
        // 表格数据值
        // let tableDataList = JSON.parse(tableData).data;
        // console.log(  tableData.length,  tableArray.length)
        let leaveH = 0 // 剩余可展示高度

        // this.nextDomH =tableHeadClass//-t

        if (Math.floor(boxH - surplusH) > pageH) {
          // leaveH = Math.floor(pageH - tableHeadClass)
          leaveH = Math.floor(pageH)
        } else {
          leaveH = Math.floor(boxH - surplusH)
        }
        let endLeaveH = leaveH - tableHeadClass
        // 剩余高度减去表头高度,tableBody高度
        // let endLeaveH = leaveH//-t
        if (tableArray.length == 1 && tableArray[0].offsetHeight > endLeaveH) {
          let c = {
            data: tableData.slice(0, tableData.length),
            config: config,
            name: tableName
          }
          secondData = {
            data: JSON.stringify(c),
            detailType: item.detailType,
            htmlId: item.htmlId
          }
          secondID = item.htmlId
          this.nextDomH = boxH + 10
        } else if (tableArray[0].offsetHeight > endLeaveH) {

          // 如果一列都放不下
          let c = {
            data: tableData.slice(0, tableData.length),
            config: config,
            name: tableName
          }
          secondData = {
            data: JSON.stringify(c),
            detailType: item.detailType,
            htmlId: item.htmlId
          }
          secondID = item.htmlId
          this.nextDomH = boxH + 10
        } else {
          if (this.deleteNum != 0) {
            tableArray = tableArray.slice(this.deleteNum, tableArray.length) // 对数据截取处理
          }
          let tableAddH = tableHeadClass // 表格每行数据累加高度 初始时加上表头高度

          // offsetHeight获取 存在延迟性 故使用定值  padding 上下为6  文字行高为24 ,当文字超过5 需要换行 cityName定宽98(6个字) areaName/areaType定宽148(最大13个字换行10个字) 一个文字宽度为15左右
          // console.log(tableData, tableArray.length, item, tableArray);

          for (let i = 0; i < tableArray.length; i++) {

            // 判断两个属性那个行高更高
            // console.log(tableArray[i].childNodes );
            let cityName = tableData[i] ? tableData[i].cityName : null;
            let areaName = tableData[i] ? tableData[i].areaName ? tableData[i].areaName : tableData[i].areaType : null;
            // console.log( areaName);
            if( cityName == null || areaName == null || cityName.length < 6 || areaName.length < 13 ) {
              tableAddH += tableArray[i].offsetHeight
            }else {
              if( cityName.length / 6 >= areaName.length / 10 ) {
                console.log( 6 + parseInt( cityName.length / 6 + 1 ) * 24 )
                // tableAddH += 6 + parseInt( cityName.length / 6 + 1 ) * 30;
              }else {
                console.log( 6 + parseInt( areaName.length / 10 + 1 ) * 24 )
                // tableAddH += 6 + parseInt( areaName.length / 10 + 1 ) * 30;
              }
            }

            if (  tableAddH > endLeaveH - 30 && ifBreak == 1  ) {
            // if (  tableAddH >= endLeaveH && ifBreak == 1  ) {//-t 如果表格内容大于剩下的高度 则截取
              breakNum = i // 从何处截断数据
              // console.log( i );
              ifBreak = -1
            } else if (tableAddH < endLeaveH - 30) {
              // } else if (tableAddH < endLeaveH ) { //如果表格内容小于 -t
              useNum = tableAddH // 能占用高度
            }
          }
          // 当表格的最后一个正好在页尾处时，需要把最后一个从起一页；
          // let endIndex = tableData.length == breakNum? breakNum - 1 : breakNum;
          let endIndex = breakNum;
          // let endUseNum = tableData.length == breakNum? useNum - 30 : useNum;
          let endUseNum = useNum
          // this.nextDomH +=(leaveH-endUseNum)//-t

          // ifNext = tableArray.length == breakNum ? false : true;
          // this.page = tableData.length == breakNum? this.page - 1 : this.page;

          this.deleteNum += breakNum //一个表格多页截断
          let c = {
            data: tableData.slice(0, endIndex),
            config: config
          }
          if( breakNum > tableData.length &&  tableData.length !== 0 ) {
            //surplusH 超出页面的高度 item当前项 page当前页面数 pageH页面高度
            c.name = tableName;
          }
          // console.log( tableData, endIndex, c, c.data )
          if (c.data && c.data.length > 0) {
            // console.log(c.data.length, JSON.stringify(c));
            firstData = {
              data: JSON.stringify(c),
              detailType: item.detailType,
              htmlId: `${item.htmlId}ids${page}`
            }

            this.dataArr = this.dataArr.concat(firstData)
            this.ids = this.ids.concat(firstData.htmlId)
          }

          let d = {
            data: tableData.slice(endIndex, tableData.length),
            config: config,
            name: tableName
          }

          secondData = {
            data: JSON.stringify(d),
            detailType: item.detailType,
            htmlId: item.htmlId
          }
          secondID = item.htmlId




          // 如果超出的高度大于一页的高度，就不用加10 否则要加10
          this.nextDomH = tableAddH - endUseNum + tableHeadClass // 要把表头的高度也加上
          // this.nextDomH +=surplusH

          if (this.nextDomH > pageH) {
            this.nextDomH += 0
          } else {
            this.nextDomH += 10
          }

          // console.log( boxH, surplusH, leaveH, tableAddH, endUseNum, endLeaveH, tableHeadClass )
        }
        // 文字时
      } else if (item.detailType == '5') {
        let itemData = JSON.parse(item.data).data
        let canUseH = Math.floor(boxH - surplusH) // 剩余可用高度
        let len = Math.floor((boxH - surplusH) / 24) //剩余的行数
        let newDivText = '' //文字内容
        let breakpoint = 0 // 在哪里截断
        for (var i = 0; i < itemData.length; i++) {
          newDivText += itemData[i]
          this.newDiv.innerHTML =
            '<p class="word-text" style="width:643.69px;">' +
            newDivText +
            '</p>'
          if (this.newDiv.offsetHeight > canUseH) {
            // 当高度超出是截断
            breakpoint = i
            break
          }
        }
        let c = {
          data: itemData.substring(0, breakpoint)
        }
        firstData = {
          data: JSON.stringify(c),
          detailType: item.detailType,
          htmlId: `${item.htmlId}ids${page}`
        }
        this.dataArr = this.dataArr.concat(firstData)
        this.ids = this.ids.concat(firstData.htmlId)
        let d = {
          data: itemData.substring(breakpoint, itemData.length)
        }
        secondData = {
          data: JSON.stringify(d),
          detailType: item.detailType,
          htmlId: item.htmlId
        }
        secondID = item.htmlId
        this.nextDomH = surplusH + 20
        // Echarts图表时
      } else if (item.detailType == 10) {
        let jsonData = JSON.parse(item.data)
        let c = {
          data: jsonData
        }
        secondData = {
          data: item.data,
          detailType: item.detailType,
          htmlId: item.htmlId
        }
        secondID = item.htmlId
        this.nextDomH = boxH + 20 // 放到下一页时所占高度
        // 其余情况直接下一页显示
      } else if (item.detailType == 13) {
        let jsonData = JSON.parse(item.data).data
        let c = {
          data: jsonData,
          cssName: JSON.parse(item.data).cssName
        }
        secondData = {
          data: JSON.stringify(c),
          detailType: item.detailType,
          htmlId: item.htmlId
        }
        secondID = item.htmlId
        this.nextDomH = boxH + 10 // 放到下一页时所占高度
      } else {
        let jsonData = JSON.parse(item.data).data
        let c = {
          data: jsonData
        }
        secondData = {
          data: JSON.stringify(c),
          detailType: item.detailType,
          htmlId: item.htmlId
        }
        secondID = item.htmlId
        this.nextDomH = boxH + 10 // 放到下一页时所占高度
      }

      // console.log( secondData )
      // console.log( this.dataArr, item );
      // 切分页第一页数据
      if( this.dataArr.length !== 0 ) {

        this.list.forEach(item => {
          if (item.page == page) {
            item.data = this.dataArr
            item.ids = this.ids
          }
        })
        this.page++
      }


      // 切分页第二页数据
      if (this.nextDomH > pageH && ifNext ) {
        surplusH = this.nextDomH - pageH
        this.dataArr = []
        this.ids = []
        this.list[this.page - 1] = {
          page: this.page,
          data: [],
          ids: []
        }
          // console.log('22222222222222222222222222');
        this.ClientDom(surplusH, secondData, this.page, pageH)
      }
      this.deleteNum = 0
      if (this.testNum == 0) {
        this.dataArr = []
        this.ids = []
        // console.log( secondData, JSON.parse(secondData.data))

        if( !JSON.parse(secondData.data).data || JSON.parse(secondData.data).data.length > 0 ) {
          this.dataArr.push(secondData) // 将切分出的第二段数据塞入下一页
          this.ids.push(secondID)
        }
        this.list[this.page - 1] = {
          page: this.page,
          data: this.dataArr,
          ids: this.ids
        }
      }
      this.testNum = 1
      store.commit('home/getList', this.list)
      setTimeout(() => {
        this.$emit('fMethod')
      }, 100)
    },
    // 正式调用
    getPageInit1() {
      new Promise((resolve, reject) => {
        this.api
          .getReportSectionContentByFirstLevel({
            reportId: this.reportId,
            levelIndex: this.levelIndex
          })
          .then(data => {
            let dataList = data
            let code = dataList.code
            let context = dataList.data
            if (code == 1) {
              this.pageList = context

              resolve(context)
            }
          })
      }).then(context => {
        this.getpage(context)
        // alert(1);
        // this.getHeight();
      })
    },

    getHeight() {
      const targets = document.getElementsByClassName('el-table__row');
      // console.log(targets);
      for (let i = 0; i < targets.length; i++) {
        targets[i].addEventListener('click',function(e){
          // console.log(e.offsetheight);
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.pre-page {
  border: 1px dashed rgb(151, 153, 60);
}
</style>
